

import { resolveResError } from './helpers'
import { useAuthStore } from '@/store'

export function setupInterceptors(axiosInstance) {
  // 处理请求
  function reqResolve(config) {
    // 处理不需要token的请求
    if (config.needToken === false) {
      return config
    }
    // 获取token
    const { accessToken } = useAuthStore()
    if (accessToken) {
      // token: Bearer + xxx
      config.headers.satoken = `${accessToken}`
    }

    return config
  }

  function reqReject(error) {
    console.log("reqReject========" + error)
    return Promise.reject(error)
  }


  function resResolve(response) {

    // 正确获取 Axios 响应中的数据
    const { data, headers } = response
    // 从响应的 data 中获取业务数据
    const { code, message, data: responseData, timestamp } = data || {}

    if (headers['content-type']?.includes('json')) {
      if (code === 200) {
        return Promise.resolve(data)
      }

      // 根据code处理对应的操作，并返回处理后的message
      const msg = resolveResError(code, message)

      return Promise.reject({ code: code, message: msg, error: data ?? response })
    }
    return Promise.resolve(data ?? response)
  }

  async function resReject(error) {
    console.log("resReject========" + error)
    // $modal.message({ message: error?.message ?? error, type: "error" })
    return Promise.reject(error)
  }

  axiosInstance.interceptors.request.use(reqResolve, reqReject)
  axiosInstance.interceptors.response.use(resResolve, resReject)
}
